<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <BasicUpload
          :maxSize="20"
          :maxNumber="10"
          :emptyHidePreview="true"
          @change="handleChange"
          :uploadParams="uploadParams"
          :api="uploadApi"
          class="my-5"
        />
        <!-- helpText="" -->
        <!-- :accept="['image/*']" -->
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '复制链接',
              onClick: handleCopy.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: '是否要删除数据?',
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { BasicUpload } from '/@/components/Upload';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  // import { deleteFile, getFilePage } from '/@/api/infra/file';
  import { getFilePage, deleteFile } from '/@/api/backs/file/file';
  import { columns, searchFormSchema } from './file.data';
  import { getToken } from '/@/utils/auth';
  import { uploadApi } from '/@/api/sys/upload';

  defineOptions({ name: 'InfraFile' });

  const { createMessage } = useMessage();
  const { clipboardRef, copiedRef } = useCopyToClipboard();

  const uploadParams = ref({
    Authorization: 'Bearer ' + getToken(),
    // 'tenant-id': getTenantId(),
  });

  const [registerTable, { reload }] = useTable({
    title: '文件列表',
    api: getFilePage,
    columns,
    formConfig: { labelWidth: 120, schemas: searchFormSchema },
    useSearchForm: true,
    showTableSetting: true,
    showIndexColumn: false,
    beforeFetch: (params) => {
      if (params.createTime) {
        params.startTime = params.createTime[0];
        params.endTime = params.createTime[1];
        delete params.createTime;
      }
    },
    actionColumn: {
      width: 160,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
  });

  function handleChange() {
    createMessage.success('操作成功！');
    reload();
  }

  function handleCopy(record: Recordable) {
    clipboardRef.value = record.url;
    if (unref(copiedRef)) {
      createMessage.warning('复制成功');
    }
  }

  async function handleDelete(record: Recordable) {
    await deleteFile({ id: record.id });
    createMessage.success('删除成功！');
    reload();
  }
</script>
